package com.ruoyi.quartz.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.SerializationUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JsonUtil;
import com.ruoyi.common.utils.LocationUtils;
import com.ruoyi.quartz.domain.*;
import com.ruoyi.quartz.util.ApplicationContextProvider;
import com.ruoyi.system.basicInformation.bo.*;
import com.ruoyi.system.basicInformation.domain.TTerminal;
import com.ruoyi.system.basicInformation.service.*;
import com.ruoyi.system.basicInformation.service.impl.TTerminalServiceImpl;
import com.ruoyi.system.basicInformation.vo.TElectronicFenceObjectVo;
import com.ruoyi.system.basicInformation.vo.TTerminalTrajectoryVo;
import com.ruoyi.system.basicInformation.vo.TTerminalVo;
import com.ruoyi.system.service.ISysUserService;
import io.lettuce.core.output.ScoredValueListOutput;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Log4j2
@Component("ryTask")
public class RyTask {
    @Autowired
    private ITTerminalService iTTerminalService;
    @Autowired
    private ITTerminalTrajectoryService iTTerminalTrajectoryService;
    @Autowired
    private ITElectronicFenceObjectService iTElectronicFenceObjectService;
    @Autowired
    private ITElectronicFenceService itElectronicFenceService;
    @Autowired
    private ITAlarmService iTAlarmService;
    @Autowired
    private ISysUserService iSysUserService;

    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
        Console.log(StrUtil.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params) {
        Console.log("执行有参方法：" + params);
    }

    public void ryNoParams() {
        Console.log("执行无参方法");
    }

    /*同步终端游客数据*/
    public void rySynchronizationTerminalTourist() throws Exception {

        Boolean isRequest = true;
        Integer pageIndex = 1;
        Integer pageSize = 20;
        do {
            String result = httpRequestHttpClient("http://10.10.40.13:44034/api/new/terminalList", "POST", "{\"page\":{\"current\":" + pageIndex + ",\"size\":" + pageSize + "},\"params\":{\"bigCategory\":\"便携型\",\"smallCategory\":\"\",\"industry\":\"\"}}", true);
            if (StringUtils.isNotEmpty(result)) {
                TRicData tRicData = JsonUtil.parseJsonToBean(result, TRicData.class);
                if (tRicData != null && tRicData.getResult().getTotal() > 0) {
                    for (TTerminalData in : tRicData.getResult().getRecords()) {
                        TTerminal checkResult = iTTerminalService.checkIsExists(in.getTerminalId());
                        Console.log("游客===" + in.getTerminalId() + "====getTerminalId===" + in.getTerminalId() + "====checkIsExists===" + checkResult);
                        //先判断是否存在，不存在则添加数据
                        if (checkResult != null) {
                            SysUser sysUser = iSysUserService.selectUserById(checkResult.getTerminalObjectId());

                            sysUser.setUserName(in.getVehicleNo());
                            sysUser.setName(in.getVehicleNo());

                            iSysUserService.updateUserById(sysUser);
                        } else {
                            SysUser add = new SysUser();
                            add.setUserName(in.getVehicleNo());
                            add.setUserType("3");
                            add.setName(in.getVehicleNo());

                            iSysUserService.insertByAddBo(add);


                            TTerminalAddBo tTerminalAddBo = new TTerminalAddBo();
                            tTerminalAddBo.setEquipmentName(in.getSmallCategory());
                            tTerminalAddBo.setEquipmentNumber(in.getTerminalId());
                            tTerminalAddBo.setSimCard(in.getSimNo());
                            tTerminalAddBo.setTerminalType("4");
                            tTerminalAddBo.setTerminalObjectId(add.getUserId());

                            iTTerminalService.insertTaskByAddBo(tTerminalAddBo);
                        }
                    }

                }
                if (tRicData.getResult().getTotal() <= pageIndex * pageSize) {
                    isRequest = false;
                } else {
                    pageIndex++;
                }
            }
        } while (isRequest);
    }

    /*同步终端车辆数据*/
    public void rySynchronizationTerminalCar() throws Exception {
        log.info("同步终端车辆数据  ");
        Boolean isRequest = true;
        Integer pageIndex = 1;
        Integer pageSize = 20;
        do {
            String result = httpRequest("http://10.10.40.13:44034/api/new/terminalList", "POST", "{\"page\":{\"current\":" + pageIndex + ",\"size\":" + pageSize + "},\"params\":{\"bigCategory\":\"车载型\",\"smallCategory\":\"\",\"industry\":\"\"}}", true);
            if (StringUtils.isNotEmpty(result)) {
                TRicData tRicData = JsonUtil.parseJsonToBean(result, TRicData.class);
                if (tRicData != null && tRicData.getResult().getTotal() > 0) {
                    for (TTerminalData in : tRicData.getResult().getRecords()) {
                        TTerminal checkResult = iTTerminalService.checkIsExists(in.getTerminalId());
                        Console.log("车===" + in.getTerminalId() + "====getTerminalId===" + in.getTerminalId() + "====checkIsExists===" + checkResult);
                        //先判断是否存在，不存在则添加数据
                        if (checkResult != null) {

                        } else {
                            TTerminalAddBo tTerminalAddBo = new TTerminalAddBo();
                            tTerminalAddBo.setEquipmentName(in.getSmallCategory());
                            tTerminalAddBo.setEquipmentNumber(in.getTerminalId());
                            tTerminalAddBo.setSimCard(in.getSimNo());
                            tTerminalAddBo.setTerminalType("2");

                            iTTerminalService.insertTaskByAddBo(tTerminalAddBo);
                        }
                    }

                }
                if (tRicData.getResult().getTotal() <= pageIndex * pageSize) {
                    isRequest = false;
                } else {
                    pageIndex++;
                }
            }
        } while (isRequest);
    }

    /*同步终端船舶数据*/
    public void rySynchronizationTerminalShip() throws Exception {
        Boolean isRequest = true;
        Integer pageIndex = 1;
        Integer pageSize = 20;
        do {
            String result = httpRequest("http://10.10.40.13:44034/api/new/terminalList", "POST", "{\"page\":{\"current\":" + pageIndex + ",\"size\":" + pageSize + "},\"params\":{\"bigCategory\":\"船载型\",\"smallCategory\":\"\",\"industry\":\"\"}}", true);
            if (StringUtils.isNotEmpty(result)) {
                TRicData tRicData = JsonUtil.parseJsonToBean(result, TRicData.class);
                if (tRicData != null && tRicData.getResult().getTotal() > 0) {
                    for (TTerminalData in : tRicData.getResult().getRecords()) {
                        TTerminal checkResult = iTTerminalService.checkIsExists(in.getTerminalId());
                        Console.log("船===" + in.getTerminalId() + "====getTerminalId===" + in.getTerminalId() + "====checkIsExists===" + checkResult);

                        //先判断是否存在，不存在则添加数据
                        if (checkResult != null) {

                        } else {
                            TTerminalAddBo tTerminalAddBo = new TTerminalAddBo();
                            tTerminalAddBo.setEquipmentName(in.getSmallCategory());
                            tTerminalAddBo.setEquipmentNumber(in.getTerminalId());
                            tTerminalAddBo.setSimCard(in.getSimNo());
                            tTerminalAddBo.setTerminalType("3");

                            iTTerminalService.insertTaskByAddBo(tTerminalAddBo);
                        }
                    }

                }
                if (tRicData.getResult().getTotal() <= pageIndex * pageSize) {
                    isRequest = false;
                } else {
                    pageIndex++;
                }
            }
        } while (isRequest);
    }

    /*循环用户终端获取最新一条轨迹数据，同时判断终端是否越界，是否离线*/
    public void rySynchronizationTerminalAlarmByUser() throws Exception {

        List<TTerminalTrajectoryVo> tTerminalTrajectoryVoList = iTTerminalTrajectoryService.queryAlarmList();

        if (tTerminalTrajectoryVoList != null && tTerminalTrajectoryVoList.size() > 0) {
            for (TTerminalTrajectoryVo item : tTerminalTrajectoryVoList) {

                String terminalType = item.getTerminalType();
                Long objId = item.getTerminalObjectId();
                BigDecimal lng = item.getX();
                BigDecimal lat = item.getY();

                TElectronicFenceObjectQueryBo bo = new TElectronicFenceObjectQueryBo();
                bo.setObjectId(objId);
                bo.setObjectType(terminalType);
                List<TElectronicFenceObjectVo> list = iTElectronicFenceObjectService.queryList(bo);

                TAlarmAddBo tAlarmAddBo = new TAlarmAddBo();

                //如果最新数据的产生时间与当前时间超过10分钟，则视为离线
                Long limit = (System.currentTimeMillis() - item.getProduceTime().getTime()) / (1000 * 60);
                if (limit > 10) {
                    //产生离线报警
                    tAlarmAddBo.setTerminalId(objId);
                    tAlarmAddBo.setTerminalType(terminalType);
                    tAlarmAddBo.setStateType("2");
                    tAlarmAddBo.setX(lng);
                    tAlarmAddBo.setY(lat);
                    tAlarmAddBo.setContent("终端号：" + item.getEquipmentNumber() + " 已经离线:" + limit + "分钟");
                    tAlarmAddBo.setDateTime(item.getProduceTime());
                    iTAlarmService.insertByTerminalAddBo(tAlarmAddBo);
                }
                Console.log("终端ID===" + objId + "====参与的围栏个数===" + list.size());
                if (list.size() >= 1) {
                    for (TElectronicFenceObjectVo tElectronicFenceObjectVoItem : list) {
                        Boolean xyResult = itElectronicFenceService.checkIsExistsForXY(lng, lat, tElectronicFenceObjectVoItem.getElectronicFenceId());
                        Console.log("围栏ID===" + tElectronicFenceObjectVoItem.getElectronicFenceId() + "====lng===" + lng + "===lat===" + lat + "===xyResult===" + xyResult);
                        //判断是否越界
                        if (!xyResult) {
                            tAlarmAddBo.setTerminalId(objId);
                            tAlarmAddBo.setTerminalType(terminalType);
                            tAlarmAddBo.setStateType("1");
                            tAlarmAddBo.setX(lng);
                            tAlarmAddBo.setY(lat);
                            tAlarmAddBo.setContent("终端号：" + item.getEquipmentNumber() + "在电子围栏：" + tElectronicFenceObjectVoItem.getName() + "越界");
                            tAlarmAddBo.setDateTime(item.getProduceTime());
                            iTAlarmService.insertByTerminalAddBo(tAlarmAddBo);
                        }
                    }
                }
            }
        }
    }

    /*循环车辆，船只终端获取最新一条轨迹数据，同时判断终端是否越界，是否离线*/
    public void rySynchronizationTerminalAlarm() throws Exception {
        TTerminalQueryBo tTerminalQueryBo = new TTerminalQueryBo();
        List<TTerminalVo> tTerminalVoList = iTTerminalService.queryList(tTerminalQueryBo);
        if (tTerminalVoList != null && tTerminalVoList.size() > 0) {
            Console.log("进入rySynchronizationTerminalAlarm服务，一共有" + tTerminalVoList.size() + "条数据需要操作");
            for (TTerminalVo item : tTerminalVoList) {
                Console.log("进入rySynchronizationTerminalAlarm服务，第一层=" + item.getEquipmentNumber());
                String result = httpRequestHttpClient("http://10.10.40.15:44081/api/query/last", "POST", "{\"queries\":[{\"metric\":\"bdgfnew\",\"tags\":{\"terminalId\":\"" + item.getEquipmentNumber() + "\"}}],\"resolveNames\":true,\"backScan\":1000}", true);
//                String result = httpRequestHttpClient("http://192.168.60.45:4242/api/query/last", "POST", "{\"queries\":[{\"metric\":\"bdgfnew\",\"tags\":{\"terminalId\":\"5671270\"}}],\"resolveNames\":true,\"backScan\":1000}", true);
                Console.log("进入rySynchronizationTerminalAlarm服务，第二层");
                if (StringUtils.isNotEmpty(result)) {

                    Console.log("进入rySynchronizationTerminalAlarm服务，第三层");
                    List<TGpsData> tGpsDataList = null;

                    tGpsDataList = (List<TGpsData>) JsonUtil.parseJsonToList(result, new TypeToken<List<TGpsData>>() {
                    }.getType());

                    DecimalFormat df = new DecimalFormat("#.000000");
                    if (tGpsDataList != null && tGpsDataList.size() > 0) {
                        Console.log("进入rySynchronizationTerminalAlarm服务，tGpsDataList.get(0).getTimestamp()=" + tGpsDataList.get(0).getTimestamp() + "---tGpsDataList.get(0).getTsuid()=" + tGpsDataList.get(0).getTsuid());
                        String resultGps = getHttpGet("http://10.10.40.15:44081/api/annotation?start_time=" + tGpsDataList.get(0).getTimestamp() + "&tsuid=" + tGpsDataList.get(0).getTsuid(), "GET", "", true);
                        if (StringUtils.isNotEmpty(resultGps)) {
                            TGpsDataRecords tGpsDataRecords = JsonUtil.parseJsonToBean(resultGps, TGpsDataRecords.class);
                            if (tGpsDataRecords != null) {

                                Console.log("进入rySynchronizationTerminalAlarm服务，成功拿到终端" + item.getId() + "最新定位数据");

                                Console.log("进入rySynchronizationTerminalAlarm服务，成功拿到终端 lng:" + tGpsDataRecords.getCustom().getVLon() + "--lat:" + tGpsDataRecords.getCustom().getVLat());

                                double lng = tGpsDataRecords.getCustom().getVLon().doubleValue() / 1000000;
                                double lat = tGpsDataRecords.getCustom().getVLat().doubleValue() / 1000000;
                                Console.log("进入rySynchronizationTerminalAlarm服务，成功拿到终端 lng:" + lng + "--lat:" + lat);
                                if (item.getTerminalObjectId() != null && item.getTerminalObjectId() > 0) {
                                    Date date = DateUtils.parseDate("20" + tGpsDataRecords.getCustom().getVTime());

                                    String terminalType = item.getTerminalType();
                                    Long objId = item.getTerminalObjectId();


                                    TElectronicFenceObjectQueryBo bo = new TElectronicFenceObjectQueryBo();
                                    bo.setObjectId(objId);
                                    bo.setObjectType(terminalType);
                                    //List<TElectronicFenceObjectVo> list = iTElectronicFenceObjectService.queryList(bo);

                                    TAlarmAddBo tAlarmAddBo = new TAlarmAddBo();
                                    //如果最新数据的产生时间与当前时间超过10分钟，则视为离线
                                    Long limit = (System.currentTimeMillis() - date.getTime()) / (1000 * 60);
                                    if (limit > 10) {
                                        //产生离线报警
                                        tAlarmAddBo.setTerminalId(objId);
                                        tAlarmAddBo.setTerminalType(terminalType);
                                        tAlarmAddBo.setStateType("2");
                                        tAlarmAddBo.setX(new BigDecimal(lng));
                                        tAlarmAddBo.setY(new BigDecimal(lat));
                                        tAlarmAddBo.setContent("终端号：" + item.getEquipmentNumber() + " 已经离线:" + limit + "分钟");
                                        tAlarmAddBo.setDateTime(DateUtils.parseDate("20" + tGpsDataRecords.getCustom().getVTime()));
                                        iTAlarmService.insertByTerminalAddBo(tAlarmAddBo);
                                    }
//                                    if (list.size() >= 1) {
//                                        //判断是否越界
//                                        if (!itElectronicFenceService.checkIsExistsForXY(new BigDecimal(lng), new BigDecimal(lat), list.get(0).getElectronicFenceId())) {
//                                            tAlarmAddBo.setTerminalId(objId);
//                                            tAlarmAddBo.setTerminalType(terminalType);
//                                            tAlarmAddBo.setStateType("1");
//                                            tAlarmAddBo.setX(new BigDecimal(lng));
//                                            tAlarmAddBo.setY(new BigDecimal(lat));
//                                            tAlarmAddBo.setContent("终端号：" + list.get(0).getObjectId() + "在电子围栏：" + list.get(0).getName() + "越界");
//                                            tAlarmAddBo.setDateTime(DateUtils.parseDate(tGpsDataRecords.getCustom().getVTime()));
//                                            iTAlarmService.insertByTerminalAddBo(tAlarmAddBo);
//                                        }
//                                    }
                                }
                                TTerminalTrajectoryAddBo tTerminalTrajectoryAddBo = new TTerminalTrajectoryAddBo();
                                tTerminalTrajectoryAddBo.setTerminalId(item.getId());
                                tTerminalTrajectoryAddBo.setTerminalType(item.getTerminalType());
                                tTerminalTrajectoryAddBo.setX(new BigDecimal(lng));
                                tTerminalTrajectoryAddBo.setY(new BigDecimal(lat));
                                tTerminalTrajectoryAddBo.setProduceTime(DateUtils.parseDate("20" + tGpsDataRecords.getCustom().getVTime()));

                                iTTerminalTrajectoryService.insertByAddBo(tTerminalTrajectoryAddBo);
                            }
                        }
                    }
                }
            }
        }
    }

    /*每天0点更新，上一天的轨迹里程，累加*/
    public void rySynchronizationTerminalMileage() throws Exception {
        TTerminalQueryBo bo = new TTerminalQueryBo();
        List<TTerminalVo> tTerminalVos = iTTerminalService.queryList(bo);
        TTerminalTrajectoryQueryBo bo1 = null;
        Date s = getTodayStartTime(true);
        Date e = getTodayEndTime(true);
        for (TTerminalVo vo : tTerminalVos) {
            bo1 = new TTerminalTrajectoryQueryBo();
            bo1.setTerminalType(vo.getTerminalType());
            bo1.setTerminalId(vo.getId());
            bo1.setBeginDate(s);
            bo1.setOverDate(e);
            List<TTerminalTrajectoryVo> tTerminalTrajectoryVos = iTTerminalTrajectoryService.queryList(bo1);
            if (tTerminalTrajectoryVos.size() > 1) {  //
                double mileage = 0f;
                for (Integer i = 0, j = 1; i < tTerminalTrajectoryVos.size() - 1; i++, j++) {
                    mileage += LocationUtils.getDistance(
                            tTerminalTrajectoryVos.get(i).getX().doubleValue(),
                            tTerminalTrajectoryVos.get(i).getY().doubleValue(),
                            tTerminalTrajectoryVos.get(j).getX().doubleValue(),
                            tTerminalTrajectoryVos.get(j).getY().doubleValue()
                    );
                }
                TTerminalEditBo editBo = new TTerminalEditBo();
                editBo.setId(vo.getId());
                editBo.setBefDayMileage(new BigDecimal(mileage).add(vo.getBefDayMileage()));
                iTTerminalService.updateByEditBo(editBo);
                TTerminalMileageAddBo addBo = new TTerminalMileageAddBo();
                addBo.setMileageNum(new BigDecimal(mileage));
                addBo.setTerminalId(vo.getId());
                addBo.setProduceTime(new Date());
                iTTerminalService.insertMileage(addBo);
            }
        }
    }

    /*每隔5分钟，更新一次里程*/
    public void rySynchronizationTerminalMileageForDay() throws Exception {
        TTerminalQueryBo bo = new TTerminalQueryBo();
        List<TTerminalVo> tTerminalVos = iTTerminalService.queryList(bo);
        TTerminalTrajectoryQueryBo bo1 = null;
        Date s = getTodayStartTime(false);
        Date e = getTodayEndTime(false);
        for (TTerminalVo vo : tTerminalVos) {
            bo1 = new TTerminalTrajectoryQueryBo();
            bo1.setTerminalType(vo.getTerminalType());
            bo1.setTerminalId(vo.getId());
            bo1.setBeginDate(s);
            bo1.setOverDate(e);
            List<TTerminalTrajectoryVo> tTerminalTrajectoryVos = iTTerminalTrajectoryService.queryList(bo1);
            if (tTerminalTrajectoryVos.size() > 1) {  //
                double mileage = 0f;
                for (Integer i = 0, j = 1; i < tTerminalTrajectoryVos.size() - 1; i++, j++) {
                    mileage += LocationUtils.getDistance(
                            tTerminalTrajectoryVos.get(i).getX().doubleValue(),
                            tTerminalTrajectoryVos.get(i).getY().doubleValue(),
                            tTerminalTrajectoryVos.get(j).getX().doubleValue(),
                            tTerminalTrajectoryVos.get(j).getY().doubleValue()
                    );
                }
                TTerminalEditBo editBo = new TTerminalEditBo();
                editBo.setId(vo.getId());
                editBo.setDayMileage(new BigDecimal(mileage));
                iTTerminalService.updateByEditBo(editBo);
            }
        }
        iTTerminalService.deleteTerminalOnline();
        iTTerminalService.insertTerminalOnline();
    }

    public static Date getTodayStartTime(boolean yesterday) {
        Calendar todayStart = Calendar.getInstance();
        if (yesterday)
            todayStart.add(Calendar.DAY_OF_MONTH, -1);
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        return todayStart.getTime();
    }

    public static Date getTodayEndTime(boolean yesterday) {
        Calendar todayEnd = Calendar.getInstance();
        if (yesterday)
            todayEnd.add(Calendar.DAY_OF_MONTH, -1);
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        return todayEnd.getTime();
    }

    /*
     * urlStr-请求地址
     * requestMethod-请求方式
     * requestParams-json参数字符串
     * isSecretCode-是否使用此参数
     * */
    private String httpRequest(String urlStr, String requestMethod, String requestParams, Boolean isSecretCode) {
        OutputStreamWriter out = null;
        BufferedReader br = null;
        String result = "";
        try {
            URL url = new URL(urlStr);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //请求方式
            conn.setRequestMethod(requestMethod);

            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            if (isSecretCode) {
                conn.setRequestProperty("secretCode", "8deabf5c4b4f44c3a6c79c4a5e260d63-0");
            }


            //DoOutput设置是否向httpUrlConnection输出，DoInput设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
            conn.setDoOutput(true);
            conn.setDoInput(true);
            /**
             * 下面的三句代码，就是调用第三方http接口
             */
            //获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //发送请求参数即数据
            out.write(requestParams);
            //flush输出流的缓冲
            out.flush();
            if (conn.getResponseCode() == 400) {
                Console.log("根据终端ID取轨迹数据接口报错" + "=====" + requestParams);
                return "";
            }
            /**
             * 下面的代码相当于，获取调用第三方http接口后返回的结果
             */
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
                result += str;
            }

            //关闭流
            is.close();
            //断开连接，disconnect是在底层tcp socket链接空闲时才切断，如果正在被其他线程使用就不切断。
            conn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    private String httpRequestHttpClient(String urlStr, String requestMethod, String requestParams, Boolean isSecretCode) {
        HttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost(urlStr);
        String result = "";
        try {
            StringEntity postingString = new StringEntity(requestParams,
                    "utf-8");
            if (isSecretCode) {
                request.setHeader("secretCode", "8deabf5c4b4f44c3a6c79c4a5e260d63-0");
                request.setHeader("accept", "*/*");
                request.setHeader("connection", "Keep-Alive");
                request.setHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
                request.setHeader("Content-Type", "application/json;charset=utf-8");
            }
            request.setEntity(postingString);
            HttpResponse resp = client.execute(request);
            //获取Http状态码
            int responseStatusCode = resp.getStatusLine().getStatusCode();
            if (responseStatusCode == 400) {
                Console.log("根据终端ID取轨迹数据接口报错" + "=====" + requestParams);
                return "";
            }
            HttpEntity entity = resp.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");//解析返回数据

                System.out.println(result);

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    public static String getHttpGet(String urlStr, String requestMethod, String requestParams, Boolean isSecretCode) {
        StringBuffer sb = new StringBuffer(urlStr);
        String data = "";
        // 创建请求对象
        HttpGet httpGet = new HttpGet(sb.toString());
        httpGet.setHeader("secretCode", "8deabf5c4b4f44c3a6c79c4a5e260d63-0");
        // 设置参数
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 5000);
        HttpConnectionParams.setSoTimeout(params, 5000);
        // 执行请求的对象
        HttpClient client = new DefaultHttpClient(params);
        // 执行请求镀锡
        try {
            HttpResponse resp = client.execute(httpGet);

            // 判断是否响应成功
            if (resp.getStatusLine().getStatusCode() == 200) {
                // 获取响应 的数据
                HttpEntity entity = resp.getEntity();

                data = EntityUtils.toString(entity, "utf-8");
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return data;
    }


}
